#include "../include/list.h"

Node *head;
static Node *curr;

void list_init()
{
    head = malloc(sizeof(Node));
    if(head == NULL)
    {
        printf("链表头结点创建失败\n");
        exit(1);
    }
    head->prev = head;
    head->next = head;
}

void curr_init()
{
    curr = head->next;
}

void insert_tail(const char *input)
{
    Node *new_node = malloc(sizeof(Node));
    if(new_node == NULL)
    {
        printf("链表结点创建失败\n");
        exit(1);
    }

    memset(new_node->name, 0, sizeof(new_node->name));
    memset(new_node->image_path, 0, sizeof(new_node->image_path));

    char *p = strtok(input, "@");
    strncpy(new_node->name, p, sizeof(new_node->name));
    p = strtok(NULL, "@");
    new_node->quantity = strtol(p, NULL, 10);
    p = strtok(NULL, "@");
    new_node->price = strtol(p, NULL, 10);
    p = strtok(NULL, "@");
    strncpy(new_node->image_path, p, sizeof(new_node->image_path));

    new_node->prev = head->prev;
    new_node->next = head;
    head->prev->next = new_node;
    head->prev = new_node;
}

void set_curr_prev()
{
    curr = curr->prev;
    if(curr == head)
    {
        curr = curr->prev;
    }
}

void set_curr_next()
{
    curr = curr->next;
    if(curr == head)
    {
        curr = curr->next;
    }
}

const char *get_curr_path()
{
    return curr->image_path;
}

const char *get_curr_name()
{
    return curr->name;
}

Node *find_node(const char *str)
{
    Node *p = head->next;
    while(p != head && strcmp(p->name, str) != 0)
    {
        p = p->next;
    }
    if(p == head)
    {
        return NULL;
    }
    return p;
}

void remove_node(Node *p)
{
    p->next->prev = p->prev;
    p->prev->next = p->next;
    p->prev = NULL;
    p->next = NULL;
    free(p);
}

void add_commodity_info()
{
    FILE *fp = fopen("commodity_info.txt", "a+");
    if(fp == NULL)
    {
        perror("commodity_info.txt打开失败");
        exit(1);
    }
    char buf[1000] = {0};
    snprintf(buf, sizeof(buf), "%s@%ld@%ld@%s\n", head->prev->name, head->prev->quantity, head->prev->price, head->prev->image_path);
    fputs(buf, fp);
    fclose(fp);
}

void overwrite_commodity_info()
{
    Node *p = head->next;
    FILE *fp = fopen("commodity_info.txt", "w+");
    if(fp == NULL)
    {
        perror("commodity_info.txt打开失败");
        exit(1);
    }
    while(p != head)
    {
        char buf[1000] = {0};
        snprintf(buf, sizeof(buf), "%s@%ld@%ld@%s\n", p->name, p->quantity, p->price, p->image_path);
        fputs(buf, fp);
        p = p->next;
    }
    fclose(fp);
}